/**
  ******************************************************************************
  * @file    main.c
  * @author  AE Team
  * @version 1.0.3
  * @date    2024-05-28
  * @brief   本样例演示多机通信，发送并接收16字节
  *          UART1作为主机，UART2作为从机
  *
  * @note    硬件平台：SYM32L010_StartKit_V1.0
  *          接线说明：断开J12、J13、J23
  *
  *          短接   CH343.RXD    与 UART2.TXD@PB02
  *          短接 UART1.TXD@PA06 与 UART2.RXD@PA04
  *
  *          主机发送数据到从机
  *          从机发送数据到电脑
  *          电脑开启助手查现象
  *          当接收地址不匹配时
  *          按下按键退出等待
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2024 SIYIMicro.
  * All rights reserved.</center></h2>
  *
  *
  ******************************************************************************
  */


/******************************************************************************/
/* Include files                                                              */
/******************************************************************************/
#include "main.h"
#include "sym32l010_hal_sysctrl.h"
#include "sym32l010_hal_systick.h"
#include "sym32l010_hal_gpio.h"
#include "sym32l010_hal_uart.h"
#include "sym32l010_startkit_board.h"

/******************************************************************************/
/* Local pre-processor symbols/macros ('#define')                             */
/******************************************************************************/

/******************************************************************************/
/* Global variable definitions (declared in header file with 'extern')        */
/******************************************************************************/
UART_HandleTypeDef hUartMaster, hUartSlave;

/******************************************************************************/
/* Local type definitions ('typedef')                                         */
/******************************************************************************/

/******************************************************************************/
/* Local function prototypes ('static')                                       */
/******************************************************************************/
static void UART_Master_Init(void);
static void UART_Slave_Init(void);

/******************************************************************************/
/* Local variable definitions ('static')                                      */
/******************************************************************************/

/******************************************************************************/
/* Local pre-processor symbols/macros ('#define')                             */
/******************************************************************************/

/******************************************************************************/
/* Function implementation - global ('extern') and local ('static')           */
/******************************************************************************/


/*******************************************************************************
 ** \brief  Main function of project
 **
 ** \return uint32_t return value, if needed
 **
 **
 ******************************************************************************/
int32_t main(void)
{
    uint8_t MasterTxRxBuf[22], SlaveTxRxBuf[22];

    // 初始化系统时钟
    HAL_SysCtrl_ConfigWaitCycle(48000000);
    HAL_SysCtrl_HSI_SetDiv(HSIOSC_TO_HSI48MHZ);

    // 初始化SysTick
    HAL_InitTick(48000000);

    // 板载Key初始化
    Bsp_Key_Init();

    // 主机 UART 初始化
    UART_Master_Init();

    // 从机 UART 初始化
    UART_Slave_Init();

    //------------------------------------------------------------
    for (uint8_t i = 0; i < 16; i++)
    {
        MasterTxRxBuf[i] = 0x50 + i;
    }

    //------------------------------------------------------------
    // 每接收16字节，则返回16字节。
    // 请通过串口助手查看UartSlave的状态
    while (1)
    {
        //--------------------------------------------------------
        // 主机以地址0x50发送16字节，从机应收不到数据
        HAL_UART_Receive_IT(&hUartSlave, SlaveTxRxBuf, 16);           // 从机准备中断接收数据

        HAL_UART_SendHalfWord(hUartMaster.Instance, 0x100 | 0x50);    // 主机发送起始地址
        HAL_UART_Transmit(&hUartMaster, MasterTxRxBuf + 1, 15, 0);    // 主机发送数据数据部分

        if (hUartSlave.RxXferCount != 0)                              // 判断从机是否接收到16个字节
        {
            printf("\r\nUartSlave Receive None, Please push KEY to Continue.\r\n");
            while (BSP_KEY_GETVALUE());                               // 按下按键可以退出等待
            while (BSP_KEY_GETVALUE() == 0);                          // 等待松手
        }

        //--------------------------------------------------------
        // 主机以地址0x5F发送16字节，从机应收到数据
        HAL_UART_Receive_IT(&hUartSlave, SlaveTxRxBuf, 16);           // 从机准备中断接收数据

        HAL_UART_SendHalfWord(hUartMaster.Instance, 0x100 | 0x5F);    // 主机发送起始地址
        HAL_UART_Transmit(&hUartMaster, MasterTxRxBuf + 1, 15, 0);    // 主机发送数据数据部分

        if (HAL_UART_Receive_IT_IsComplete(&hUartSlave) != HAL_OK)    // 判断从机是否接收完成
        {
            printf("\r\nUartSlave Receive Addr = 0x5F Error.\r\n");
            while (1);
        }
        printf("\r\nUartSlave Receive Addr = 0x5F PASS.\r\n");
        for (uint32_t i = 0; i < (hUartSlave.RxXferSize - hUartSlave.RxXferCount); i++) // 从机将接收到的数据发送到PC
        {
            printf("%2X ", SlaveTxRxBuf[i]);
        }

        //--------------------------------------------------------
        // 主机以地址0x5E发送16字节，从机应收到数据
        HAL_UART_Receive_IT(&hUartSlave, SlaveTxRxBuf, 16);           // 从机准备中断接收数据

        HAL_UART_SendHalfWord(hUartMaster.Instance, 0x100 | 0x5E);
        HAL_UART_Transmit(&hUartMaster, MasterTxRxBuf + 1, 15, 0);

        if (HAL_UART_Receive_IT_IsComplete(&hUartSlave) != HAL_OK)
        {
            printf("\r\nUartSlave Receive Addr = 0x5E Error.\r\n");
            while (1);
        }
        printf("\r\nUartSlave Receive Addr = 0x5E PASS.\r\n");
        for (uint32_t i = 0; i < (hUartSlave.RxXferSize - hUartSlave.RxXferCount); i++) // 从机将接收到的数据发送到PC
        {
            printf("%2X ", SlaveTxRxBuf[i]);
        }

        //--------------------------------------------------------
        // 主机以地址0xFF发送16字节，从机应收到数据
        HAL_UART_Receive_IT(&hUartSlave, SlaveTxRxBuf, 16);

        HAL_UART_SendHalfWord(hUartMaster.Instance, 0x100 | 0xFF);
        HAL_UART_Transmit(&hUartMaster, MasterTxRxBuf + 1, 15, 0);
        if (HAL_UART_Receive_IT_IsComplete(&hUartSlave) != HAL_OK)
        {
            printf("\r\nUartSlave Receive Addr = 0xFF Error.\r\n");
            while (1);
        }
        printf("\r\nUartSlave Receive Addr = 0xFF PASS.\r\n");
        for (uint32_t i = 0; i < (hUartSlave.RxXferSize - hUartSlave.RxXferCount); i++) // 从机将接收到的数据发送到PC
        {
            printf("%2X ", SlaveTxRxBuf[i]);
        }

        printf("\r\n");
        printf("\r\n");
        printf("\r\n");
    }
}


/*******************************************************************************
 * @brief  UART多机通信主机初始化
 * @param  None
 * @retval None
 */
static void UART_Master_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    MemClr(&GPIO_InitStruct, sizeof(GPIO_InitStruct));

    // 使能外设时钟
    HAL_SYSCTRL_UART1_CLK_ENABLE();
    HAL_SYSCTRL_GPIOA_CLK_ENABLE();

    // 配置PA06为UART1.TXD
    AFx_UART1TXD_PA06();
    GPIO_InitStruct.Pins = GPIO_PIN_6;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    HAL_GPIO_Init(SYM_GPIOA, &GPIO_InitStruct);

    // 配置UART1作为多机通信的主机
    MemClr(&hUartMaster, sizeof(hUartMaster));

    hUartMaster.Instance = SYM_UART1;
    hUartMaster.RxDoneFun         = UART_RXDONE_FIXLEN;               // 按照固定长度接收
    hUartMaster.Init.ClockSource  = UART_CLKSRC_PCLK;
    hUartMaster.Init.PclkFreq     = 48000000;
    hUartMaster.Init.BaudRate     = 115200;                           // Baud = 115200
    hUartMaster.Init.ParityMode   = UART_PARITYMODE_CUSTOM;           // 自定义校验位
    hUartMaster.Init.StopBits     = UART_STOPBITS_1;                  // STOP = 1
    HAL_UART_Init(&hUartMaster);                                      // 初始化UART
    HAL_UART_TXD_Enable(hUartMaster.Instance);                        // 使能UART的TXD功能
    HAL_UART_RXD_Enable(hUartMaster.Instance);                        // 使能UART的RXD功能
}


/*******************************************************************************
 * @brief  UART多机通信从机初始化
 * @param  None
 * @retval None
 */
static void UART_Slave_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    MemClr(&GPIO_InitStruct, sizeof(GPIO_InitStruct));

    // 使能外设时钟
    BSP_UART_PERIPH_CLK_ENABLE();
    BSP_UART_RXD_PORT_PERIPH_CLK_ENABLE();
    BSP_UART_TXD_PORT_PERIPH_CLK_ENABLE();

    // 配置PB02为UART2.TXD
    AFx_UART2TXD_PB02();
    GPIO_InitStruct.Pins = GPIO_PIN_2;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    HAL_GPIO_Init(SYM_GPIOB, &GPIO_InitStruct);

    // 配置PA04为UART2.RXD
    AFx_UART2RXD_PA04();
    GPIO_InitStruct.Pins = GPIO_PIN_4;
    GPIO_InitStruct.Pull = GPIO_PULL_UP;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    HAL_GPIO_Init(SYM_GPIOA, &GPIO_InitStruct);

    // 配置UART2作为多机通信的从机
    MemClr(&hUartSlave, sizeof(hUartSlave));

    hUartSlave.Instance = SYM_UART2;
    hUartMaster.RxDoneFun         = UART_RXDONE_FIXLEN;               // 按照固定长度接收
    hUartSlave.Init.ClockSource   = UART_CLKSRC_PCLK;
    hUartSlave.Init.SlaveAddr     = 0x5F;
    hUartSlave.Init.SlaveAddrMask = 0xFE;                             // 有效地址:0x5F/0x5E
    hUartSlave.Init.SlaveAddrEn   = UART_SLAVEADDR_ENABLE;
    hUartSlave.Init.PclkFreq      = 48000000;
    hUartSlave.Init.BaudRate      = 115200;
    hUartSlave.Init.ParityMode    = UART_PARITYMODE_CUSTOM;           // 自定义校验位
    hUartSlave.Init.StopBits      = UART_STOPBITS_1;                  // STOP = 1
    HAL_UART_Init(&hUartSlave);                                       // 初始化UART
    HAL_UART_TXD_Enable(hUartSlave.Instance);                         // 使能UART的TXD功能
    HAL_UART_RXD_Enable(hUartSlave.Instance);                         // 使能UART的RXD功能
    NVIC_ClearPendingIRQ(UART2_IRQn);
    NVIC_EnableIRQ(UART2_IRQn);
}


/*******************************************************************************
 ** EOF (not truncated)
 ******************************************************************************/
#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
    /* USER CODE BEGIN */
    /* User can add his own implementation to report the file name and line number,
       tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* USER CODE END */
}
#endif /* USE_FULL_ASSERT */


/************************ (C) COPYRIGHT SIYIMicro *****END OF FILE*************/
